package io.netty.study.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.java.Log;

/**
 * @author YueGod
 * @since 2024/4/19
 */
@Log
public class NettyServerStart {

    private final int port;

    public NettyServerStart(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        // Netty使用的是主从Reactor线程模型，主线程负责接收客户端的连接，从线程负责具体的业务处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new EchoServerHandler());
                        }
                    })
                    // 设置TCP缓冲区
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 保持连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，开始接收进来的连接
            ChannelFuture f = b.bind(port).sync().addListener(future -> {
                if (future.isSuccess()) {
                    log.info("服务端启动成功");
                } else {
                    log.info("服务端启动失败");
                }
            });
            // 等待服务器 socket 关闭。
            f.channel().closeFuture().sync().addListener(future -> {
                if (future.isSuccess()) {
                    log.info("服务端关闭成功");
                } else {
                    log.info("服务端关闭失败");
                }
            });
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new NettyServerStart(port).start();
    }
}

@Log
class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(io.netty.channel.ChannelHandlerContext ctx, Object msg) {
        log.info("Server received: " + msg);
        ctx.write(msg);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(io.netty.channel.ChannelHandlerContext ctx, Throwable cause) {
        log.info("exceptionCaught");
        ctx.close();
    }
}